package com.wuyou.dataStructure.tree;

import org.springframework.boot.web.embedded.tomcat.TomcatReactiveWebServerFactory;
import sun.applet.Main;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 二叉树中序遍历
 * 左-根-右
 */
public class InorderTraversal {

    public static void main(String[] args) {

    }


    public List<Integer> sol_1(TreeNode root){
        List<Integer> ans = new ArrayList<>();
        return preOrder(root, ans);
    }

    public List<Integer> preOrder(TreeNode root, List<Integer> ans){
        if (root == null) {
            return ans;
        }
        preOrder(root.left, ans);
        ans.add(root.val);
        preOrder(root.right, ans);
        return ans;
    }

    /**
     * 栈处理
     * @param root
     * @return
     */
    public List<Integer> sol_2(TreeNode root){
        List<Integer> res = new ArrayList<>();
        //加个边界条件判断
        if (root == null)
            return res;
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            if (!stack.isEmpty()) {
                root = stack.pop();
                res.add(root.val);
                root = root.right;
            }
        }
        return res;
    }

}
